import 'dart:async';
import 'dart:io';
import 'package:get/get.dart';
import 'package:second_hand/API/file/file.dart';
import 'package:second_hand/data/shared_preferences_service.dart';
import '../../data/add_goods_data.dart';
import '../request_ways.dart';

class ItemApiService {
  static const String baseUrl = "http://39.107.246.135:1224";
  static const int timeoutSeconds = 10;

  // 分页查询商品列表接口
  static Future<Map<String, dynamic>> searchGoods({
    required int page,
    String? keyword,
    String? category,
    String? campus,
    double? min_price,
    double? max_price,
    String? sort_by_price,
  }) async {
    final token = await SharedPreferencesService.getToken();
    if (token == null) {
      return {'code': '401', 'message': '未登录'}; // 明确错误码
    }
    final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    // 修复1: 所有数值参数明确格式化为字符串
    final queryParams = {
      'page': page.toString(),
      '_t': timestamp, // 禁用缓存
      if (keyword != null) 'keyword': keyword,
      if (category != null) 'category': category,
      if (campus != null) 'campus': campus,
      if (min_price != null) 'min_price': min_price.toStringAsFixed(2),
      if (max_price != null) 'max_price': max_price.toStringAsFixed(2),
      if (sort_by_price != null) 'sort_by_price': sort_by_price,
    };

    // 使用更安全的URL构建方式
    final uri = Uri.parse(baseUrl).replace(
      path: '/item/search',
      queryParameters: queryParams,
    );
    print('分页请求 URL: $uri'); // 检查是否包含正确参数

    // 确认请求类没有重复添加参数
    final response = await Request.getRequest(
      path: uri.toString().replaceFirst(baseUrl, ""),
      header: {"Authorization": token},
      queryParams: null, // 这里应该置空，避免重复
    );
    return response;
  }
  //添加商品接口
  static Future<Map<String, dynamic>> addGoods({required String name,required double price,required String description,required category,required List<String> campuses}) async {
    try{
      final token = await SharedPreferencesService.getToken();
      final controller=Get.find<GoodsController>();
      final List<String> imageUrls=[];
      for(final file in controller.selectedImages){
        final uploadResult = await FileService.uploadFile(File(file.path), token);
        if(uploadResult['code']!=40021){
          //上传图片失败todo
          return uploadResult;
        }
        imageUrls.add(uploadResult['data'] as String);
      }
      final requestBody = {
        "name": name,
        "price": price.toStringAsFixed(2),
        "description": description,
        "category": category,
        "campuses": campuses, // 转换为数组
        "images": imageUrls,
      };
      final response = await Request.postRequest(
        path: '/item/add',
        body: requestBody,
        header: {"Authorization": token!},
      );
      if(response['code']==20011){
        controller.clearForm();
        return response;
      }
      else{
        controller.clearForm();
        return response;
      }
    }on TimeoutException {
    return {"code": 0, "message": "请求超时，请检查网络连接", "data": null};
    } on Exception catch (e) {
    return {"code": 0, "message": "请求异常: ${e.toString()}", "data": null};
    }
  }
}